package com.yc.javaee.servlet.d0618;

import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

@WebFilter(filterName = "LoginFilter",
        value = {"/0615/cart.html","/0615/myinfo.html","/0615/myorder.html"})
public class LoginFilter implements Filter {
    public void init(FilterConfig config) throws ServletException {
        // 服务器已启动就立即加载
        System.out.println(" ==========LoginFilter  init ============ ");
    }
    public void destroy() {
        System.out.println(" ==========LoginFilter  destroy ============ ");
    }
    @Override
    public void doFilter(
            ServletRequest request,     // 请求   区别 HttpServlet 的请求 HttpServletRequest request,
            ServletResponse response,   // 响应   HttpServletResponse response
            FilterChain chain           // 过滤器链
    ) throws ServletException, IOException {
        System.out.println("========= LoginFilter doFilter =============");
        // Http 的请求才能获取到 Http会话对象
        HttpServletRequest req = (HttpServletRequest) request;
        HttpSession session = req.getSession();
        String loginedUser = (String) session.getAttribute("loginedUser");

        if(loginedUser == null){
            response.setContentType("text/html;charset=utf-8");
            PrintWriter out = response.getWriter();
            out.append("<div style='text-align:center; margin:100px'>").append("请先登录系统<br>")
                    .append("<a href='用户登录.html'>回到登录页</a></div>");
            // 如果直接return 用户会看到一个白板页面
            return;
        }

        // 过滤器链的 doFilter 表示正常业务下, 就行访问下一个过滤器, 或目标资源
        // doFilter 之前的代码主要负责对请求对象的拦截
        chain.doFilter(request, response);
        // doFilter 之前的代码主要负责对响应对象的拦截

    }
}
